package org.sky.axis2.security;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;

public class MyRampartServiceClient {

	private static EndpointReference targetEPR = new EndpointReference(
			"http://localhost:8001/Axis2Service/services/MyRampartService");

	private String getAxis2ConfPath() {
		StringBuilder confPath = new StringBuilder();
		confPath.append(this.getClass().getResource("/").getPath());
		confPath.append("repository");
		return confPath.toString();
	}

	private String getAxis2ConfFilePath() {
		String confFilePath = "";
		confFilePath = getAxis2ConfPath() + "/axis2.xml";
		return confFilePath;

	}

	public void testMyRampartService() {
		Options options = new Options();
		options.setAction("urn:rampartMethod");
		options.setTo(targetEPR);
		ServiceClient sender = null;
		String confFilePath = "";
		String confPath = "";
		try {
			confPath = this.getAxis2ConfPath();
			confFilePath = getAxis2ConfFilePath();
			System.out.println("confPath======" + confPath);
			System.out.println("confFilePath====" + confFilePath);
			ConfigurationContext configContext = ConfigurationContextFactory
					.createConfigurationContextFromFileSystem(confPath,
							confFilePath);
			sender = new ServiceClient(configContext, null);
			sender.setOptions(options);

			OMFactory fac = OMAbstractFactory.getOMFactory();
			OMNamespace omNs = fac.createOMNamespace(
					"http://security.axis2.sky.org", "");
			OMElement callMethod = fac.createOMElement("rampartMethod", omNs);
			OMElement nameEle = fac.createOMElement("name", omNs);
			nameEle.setText("Wang Clare");
			callMethod.addChild(nameEle);
			OMElement response = sender.sendReceive(callMethod);
			System.out.println("response====>" + response);
			System.out.println(response.getFirstElement().getText());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sender != null)
				sender.disengageModule("addressing");
			try {
				sender.cleanup();
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {
		MyRampartServiceClient rampartServiceClient = new MyRampartServiceClient();
		rampartServiceClient.testMyRampartService();

	}

}